package xyz.yuanwl.demo.freemarker;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.*;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.junit.Test;

/**
 * 最常见的问题：
 * java.io.FileNotFoundException: xxx does not exist. 解决方法：要有耐心
 * FreeMarker jar 最新的版本（2.3.23）提示 Configuration 方法被弃用
 * 代码自动生产基本原理：
 * 数据填充 freeMarker 占位符
 */
public class FreemarkerDemo {

	private static final String TEMPLATE_PATH = "src/main/resources";
	private static final String CLASS_PATH = "src/main/java/xyz/yuanwl/demo/freemarker";

	@Test
	public void test1() {
		try {
			Map<String, Object> dataMap = new HashMap<>();
			dataMap.put("classPath", "xyz.yuanwl.demo.freemarker");
			dataMap.put("className", "AutoCodeDemo");
			dataMap.put("helloWorld", "通过简单的 <代码自动生产程序> 演示 FreeMarker的HelloWorld！");

			File file = new File(CLASS_PATH + "/AutoCodeDemo.java");
			Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
			write(dataMap, "hello.ftl", out);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Test
	public void test2() {
		try {
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put("name", "itdragon博客");
			dataMap.put("dateTime", new Date());

			List<User> users = new ArrayList<User>();
			users.add(new User(1, "ITDragon 博客"));
			users.add(new User(2, "欢迎"));
			users.add(new User(3, "You！"));
			dataMap.put("users", users);

			Writer out = new OutputStreamWriter(System.out);
			write(dataMap, "stringFreeMarker.ftl", out);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 输出文件
	 *
	 * @param dataMap
	 * @param ftl
	 * @param out
	 */
	private void write(Map<String, Object> dataMap, String ftl, Writer out) {
		// step1 创建freeMarker配置实例
		Configuration configuration = new Configuration();

		try {
			// step2 获取模版路径
			configuration.setDirectoryForTemplateLoading(new File(TEMPLATE_PATH));

			// step3 加载模版文件
			Template template = configuration.getTemplate(ftl);

			// step4 结合数据输出文件
			template.process(dataMap, out);

			System.out.println("文件创建成功 !");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != out) {
					out.flush();
					out.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

}